package com.bw.producer.service.fixedTime;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bw.common.redis.service.RedisService;
import com.bw.common.security.utils.SecurityUtils;
import com.bw.model.LoginUser;
import com.bw.producer.Vo.CartItemVo;
import com.bw.producer.Vo.CartVo;
import com.bw.producer.mapper.CartItemMapper;
import com.bw.producer.service.CartItemService;
import com.bw.producer.service.impl.CartItemServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
public class FixedTime {
    @Autowired
    public RedisService redisService;
    @Autowired
    public CartItemMapper cartItemMapper;


    private static final String CART_ITEM = "cart:item:";
    @Scheduled(cron = "0 0 0/5 * * ?")
    //@Scheduled(cron = "0/30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void fixedTime(){
        Collection<String> keys = redisService.keys(CART_ITEM + "*");

        //判断redis中是否有数据
        if(keys.size() == 0){
            cartItemMapper.delectCartItem();
            return;
        }

        keys.forEach(key -> {
            Map<String, CartItemVo> map = redisService.getCacheMap(key);

            List<CartItemVo> cartItemVoList = cartItemMapper.selectCartItem();

            //判断数据库是否为空
            if(cartItemVoList.size() != 0){
                cartItemMapper.delectCartItem();
            }

            map.forEach((k, v) -> {

                cartItemMapper.addCartItem(v);

            });
        });

    }
}
